package foodmaterial.security;

import foodmaterial.entity.JsonResult;
import foodmaterial.entity.ResultCode;
import foodmaterial.entity.SysUser;
import foodmaterial.utils.JsonUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 登录成功
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private SysUser createSysUser(SysUser userDetails) {
        SysUser user = new SysUser() ;
        user.setName(userDetails.getName());
        user.setId(userDetails.getId());
        user.setGrantedAuthorities((List)userDetails.getAuthorities());
        user.setDb(userDetails.getDb());
        user.setAccount(userDetails.getAccount());
        user.setCompanyName(userDetails.getCompanyName());
        user.setUserType(userDetails.getUserType());
        user.setFoodSupplyType(userDetails.getFoodSupplyType());
        return user ;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        SysUser userDetails = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        userDetails.setLastLoginTime(new Date());
        userDetails.setUpdateTime(new Date());
        //更新用户信息，自己补数据库的操作

        SysUser user = createSysUser(userDetails) ;

        JsonResult result = new JsonResult(true, ResultCode.SUCCESS,user);
        httpServletRequest.getSession().removeAttribute("validateCode");

        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JsonUtil.objectToJson(result));
    }
}
